package com.amado.course42Nio.demo2;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author wangyulong
 * @version 1.5.0
 * @date 2020/3/7 0:00
 */
public class NioClient {
    private static Selector selector = null;

    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        selector = Selector.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8080));
        socketChannel.register(selector, SelectionKey.OP_WRITE);

        while(!socketChannel.finishConnect()){

        }
        System.out.println("完成连接");
        while (selector.select() > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                iterator.remove();
                if (next.isReadable()) {
                    read(next);
                } else if (next.isWritable()) {
                    write(next);
                }
            }
        }
        System.out.println("退出");

    }

    public static void write(SelectionKey selectionKey) throws IOException {
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        String content = "你好";
        byteBuffer.put(content.getBytes());
        byteBuffer.flip();
        System.out.println("发送数据" + content);
        channel.write(byteBuffer);
        channel.register(selector, SelectionKey.OP_READ);
    }

    public static void read(SelectionKey selectionKey) throws IOException {
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        channel.read(byteBuffer);
        byteBuffer.flip();
        String receiveData = new String(Charset.forName("UTF-8").decode(byteBuffer).array());
        System.out.println("收到数据" + receiveData);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
